/*
 * @Description: MySQL增删改查，处理数据库读写问题
 * @version: V_00.00
 * @Company: SMD
 * @Author: Nick_Yang
 * @Date: 2018-12-10 17:33:55
 * @LastEditors: Nick_Yang
 * @LastEditTime: 2018-12-27 22:30:16
 */
let ESCAPE = require('./escape.js');
let escape = new ESCAPE;

class API {
  constructor(req, res, next) {
    this.req = req;
    this.res = res;
    this.next = next;
  }
  add(databases, change) { // String, Object 添加操作
    var keys = Object.keys(change);
    var value = this.handleValues(change);
    var insert = `INSERT INTO ${databases}(${keys.join(',')}) VALUES (${value.slice(1)})`;
    console.log(insert);
    return this.handlePromise(insert);
  }
  delete(databases, where) { // String, String
    var insert = `delete from ${databases} where ${where}`;
    console.log(insert);
    return this.handlePromise(insert);
  }
  edit(databases, change, where) { // String, Object, String
    var insert = `update ${databases} set ${this.handleUpdateSet(change)} where ${where}`;
    console.log(insert);
    return this.handlePromise(insert);
  }
  get(databases, where) { // String, String
    var insert = where ? `SELECT * FROM ${databases} WHERE ${where}` : `SELECT * FROM ${databases}`;
    console.log(insert);
    return this.handlePromise(insert);
  }
  handleUpdateSet(obj) { // 处理edit 下SQL语句
    var value = '';
    for (let key in obj) {
      let str = typeof obj[key] === 'string' ? `${key}="${escape.html2Escape(obj[key])}"` : `${key}=${obj[key]}`;
      value = value + `,${str}`;
    }
    return value.slice(1); // 自动拼接了','，所以要把首位删除
  }
  handleValues(obj) { // 处理add 下SQL语句
    var values = Object.values(obj);
    var value = '';
    values.forEach((item) => { // 如果是string类型，需要拼接""，否则无法正常写入
      typeof item === 'string' ? value = value + `,"${escape.html2Escape(item)}"` : value = value + `,${item}`;
    });
    return value;
  }
  handlePromise(insert) { // 处理promise，执行SQL语句，返回结果
    let self = this;
    return new Promise((resolve, reject) => {
      this.req.getConnection(function (err, connection) {
        connection.query(insert, [], function (err, results) {
          if (err) return self.next(err);
          // resolve(JSON.parse(escape.escape2Html(JSON.stringify(results))));
          let data = JSON.parse(JSON.stringify(results));
          console.log(data, 111);
          if (!(data instanceof Array)) { // 如果不是查找操作，不会返回Array
            resolve(data);
            return;
          }

          let useReset = ['note_content']; // 定义需要反编译的数组

          data.forEach(item => { // 对select进行单独的转义操作
            let arr = useReset.filter(i => {
              return item[i];
            });
            arr.forEach(items => {
              item[items] = escape.escape2Html(item[items]);
            });

          });
          resolve(data);
          // reject(err);
        });
      });
    });
  }
}

module.exports = API;